package com.da.javatest.webflux.controller;

import java.util.concurrent.TimeUnit;
import java.util.stream.IntStream;

import com.da.javatest.webflux.entity.User;
import com.da.javatest.webflux.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

/**
 * @author JokerDa.
 * @date 2021/1/6 15:24
 * Description:
 */
@RestController
public class UserController {
    @Autowired
    private UserService userService;

    // 根据ID查询用户
    @GetMapping(value = "/user/{id}")
    public Mono<User> getUserById(@PathVariable int id) {
        return userService.getUserById(id);
    }

    // 查询所有用户
    @GetMapping(value = "/user/all")
    public Flux<User> getAllUser() {
        return userService.getAllUser();
    }

    @GetMapping(value = "/flux/1", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<String> flux1() {
        Flux<String> stringFlux = Flux.fromStream(IntStream.range(1, 5).mapToObj(i -> {
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "flux data----" + i;
        }));
        return stringFlux;
    }

    // 保存用户
    @PostMapping(value = "/user/save")
    public Mono<Void> saveUser(@RequestBody User user) {
        return userService.saveUser(Mono.just(user));
    }
    //@PostMapping(value = "/user/save")
    //public Mono<Void> saveUser(ServerWebExchange exchange) {
    //    Mono<MultiValueMap<String, String>> formData = exchange.getFormData();
    //    formData.flatMap(map -> {
    //        System.out.println("from:" + map);
    //        return Mono.justOrEmpty(map.toString());
    //    });
    //    return userService.saveUser(Mono.just(null));
    //}

    // 删除用户
    @DeleteMapping(value = "/user/{id}")
    public Mono<ResponseEntity<Void>> deleteUser(@PathVariable int id) {
        return userService.deleteUser(id)
            .then(Mono.just(new ResponseEntity<Void>(HttpStatus.OK)))
            .defaultIfEmpty(new ResponseEntity<Void>(HttpStatus.NOT_FOUND));
    }
}
